<template>
  <HModal :model-value="assignDialog" @close="onCancel" width="auto">
    <template #header>
      <h3 v-if="assignAny === 1"><span v-if="isbatch">批量</span>分配客服</h3>
      <h3 v-if="assignAny === 2"><span v-if="isbatch">批量</span>分派服务商</h3>
      <h3 v-if="assignAny === 3">确认<span class="comple">完成</span>工单</h3>
      <h3 v-if="assignAny === 4">确认<span class="cancel">取消</span>工单</h3>
      <h3 v-if="assignAny === 5"><span v-if="isbatch">批量</span>催单</h3>
      <h3 v-if="assignAny === 6">改派客服</h3>
      <h3 v-if="assignAny === 7">改派服务商</h3>
      <h3 v-if="assignAny === 8">工单归档</h3>
    </template>
    <div v-loading="onsaveloading" element-loading-text="加载中...">
      <!-- <div class="title mb20" v-if="isbatch">单次最多批量操作1000条数据</div> -->
      <div v-if="isbatch" style="margin-bottom: 20px">
        <span>当前选中&nbsp;</span>
        <span style="color: #e69103">{{ selecttion.length }}</span>
        <span>&nbsp;个工单进行批量操作！</span>
      </div>
      <el-alert
        v-if="assignAny === 7"
        class="alert"
        show-icon
        :closable="false"
        title="改派后，该工单不再属于原服务商"
        type="warning"
      />
      <el-form
        label-width="80"
        ref="formRef"
        :model="ruleForm"
        :rules="rules"
        @validate="handleFormValidate"
        class="form_content"
      >
        <el-form-item
          v-if="assignAny === 1 || assignAny === 6"
          label="分配客服"
          required
          prop="empId"
          :class="{
            form_item: formValidateResult['empId'],
            validate_fail: !formValidateResult['empId'],
          }"
          label-width="70"
        >
          <el-select
            v-model="ruleForm.empId"
            placeholder="分配客服"
            filterable
            clearable
            :filter-method="getworkTeamPageSelect"
            :loading="loading"
            remote-show-suffix
          >
            <el-option
              v-for="item in customers"
              :key="item.name"
              :disabled="emp == item.name"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item v-if="assignAny === 2 && selecttion.length == 1" label="分派规则">
                    <el-radio-group v-model="ruleForm.dispatchRule" @change="onDispatchRule">
                        <el-radio :value="false">按系统规则分派(暂仅支持单个分派)</el-radio>
                        <el-radio :value="true">批量指定服务商分派</el-radio>
                    </el-radio-group>
                </el-form-item> -->
        <el-form-item v-if="assignAny === 7" label="当前服务商">
          <el-input class="inputread" :readonly="true" :value="network"></el-input>
        </el-form-item>
        <el-form-item
          v-if="assignAny === 2 || assignAny === 7"
          label="分配服务商"
          required
          prop="website"
        >
          <el-select
            class="w200"
            placeholder="分配服务商"
            filterable
            clearable
            v-model="ruleForm.website"
            :filter-method="getNetworkPageSelectList"
            :loading="loading"
            remote
            remote-show-suffix
          >
            <el-option
              v-for="item in networks"
              :key="item.name"
              :disabled="networkId == item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="assignAny === 2" label="分配人员">
          <el-select
            v-model="ruleForm.cusId"
            placeholder="分配人员"
            filterable
            clearable
            :filter-method="getNetworkEmpPageSelectList"
            :loading="loading"
            remote
            remote-show-suffix
          >
            <el-option
              v-for="item in customersList"
              :key="item.name"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="
            assignAny === 2 ||
            assignAny === 3 ||
            assignAny === 4 ||
            assignAny === 7 ||
            assignAny === 6 ||
            assignAny === 8
          "
          label="处理备注"
          style="margin: 12px 0 0 0"
          label-width="70"
        >
          <div class="notes">
            <el-input
              v-model="ruleForm.note"
              maxlength="200"
              placeholder="请输入处理备注"
              show-word-limit
              type="textarea"
              resize="both"
            />
          </div>
        </el-form-item>
        <el-form-item
          v-if="assignAny === 5"
          label="催单内容"
          required
          prop="content"
          style="margin: 0"
        >
          <div class="notes">
            <el-input
              v-model="ruleForm.content"
              maxlength="200"
              placeholder="请输入催单内容"
              show-word-limit
              type="textarea"
              resize="horizontal"
            />
          </div>
        </el-form-item>
      </el-form>
    </div>
    <template #footerRight>
      <HButton isModal type="primary" @click="onSave">保存</HButton>
      <HButton isModal @click="onCancel">取消</HButton>
    </template>
  </HModal>
</template>

<script setup lang="ts">
  import { ref, toRefs, watch, reactive } from 'vue'
  import {
    dispatchOrderEmp,
    finishOrder,
    cancelOrder,
    saveReminder,
    orderDispatchNetwork,
    changeNetwork,
    changeServiceEmp,
  } from '@/api/order'
  import { orderArchived } from '@/api/archived'
  import { getNetworkEmpPageSelect } from '@/api/network'
  import { empPageSelecct } from '@/api/organize'
  import { getNetworkPageSelect } from '@/api/network'
  import { ElMessage, FormItemProp } from 'element-plus'
  import _ from 'lodash'
  import HButton from '@/components/common/button/HButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'

  const props = defineProps({
    assignAny: Number,
    assignDialog: Boolean,
    selecttion: Array,
    isbatch: Boolean,
    networkId: String,
    network: String,
    emp: String,
  })
  const { assignAny, assignDialog, selecttion, isbatch, network, networkId, emp } = toRefs(props)
  const emits = defineEmits(['assign-dialog', 'update-list'])
  const loading = ref(false)
  const onsaveloading = ref(false)
  const customers = ref([])
  const customersList = ref([])
  const formRef = ref()
  const networks = ref(null)
  const ruleForm = reactive({
    empId: null, //客服
    website: null, //网点
    note: '', //备注
    content: '', //催单内容
    // dispatchRule: true,
    cusId: '', //分配人员
  })
  const rules = reactive({
    empId: [{ required: true, message: '请选择客服人员！', trigger: ['blur', 'change'] }],
    website: [{ required: true, message: '请选择服务商！', trigger: ['blur', 'change'] }],
    note: [{ required: true, message: '请输入处理备注!', trigger: 'blur' }],
    content: [{ required: true, message: '请输入催单内容!', trigger: 'blur' }],
  })

  /**
   * 获取客服人员下拉
   */
  const getworkTeamPageSelect = _.throttle((val: string) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    loading.value = true
    empPageSelecct(data).then((res) => {
      if (res.data.success) {
        customers.value = res.data.data.rows
      }
      loading.value = false
    })
  }, 500)

  //获取服务商下拉
  const getNetworkPageSelectList = _.throttle((val: string) => {
    loading.value = true
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    getNetworkPageSelect(data).then((res) => {
      if (res.data.success) {
        networks.value = res.data.data.rows
      }
      loading.value = false
    })
  }, 500)
  // 获取分配人员下拉
  const getNetworkEmpPageSelectList = _.throttle((val: string) => {
    if (!ruleForm.website) return
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    loading.value = true
    getNetworkEmpPageSelect(data, ruleForm.website).then((res) => {
      if (res.data.success) {
        customersList.value = res.data.data.rows
      }
      loading.value = false
    })
  }, 500)
  // 保存
  const onSave = () => {
    formRef.value.validate((valid) => {
      if (valid) {
        let data = {
          remark: ruleForm.note,
          workIds: selecttion.value,
        }
        switch (assignAny.value) {
          case 1:
            onsaveloading.value = true
            dispatchOrderEmp(selecttion.value, ruleForm.empId).then((res) => {
              if (!res) return
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  duration: 3000,
                  type: res.data.success ? 'success' : 'error',
                })
              if (res.data.success) {
                emits('update-list')
                onCancel()
              }
              onsaveloading.value = false
            })
            break
          case 2:
            let tem: any = {
              networkEmpId: ruleForm.cusId,
              networkId: ruleForm.website,
              workIds: selecttion.value,
              remark: ruleForm.note,
            }
            onsaveloading.value = true
            orderDispatchNetwork(tem).then((res) => {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  type: res.data.success ? 'success' : 'error',
                  duration: 3000,
                })
              if (res?.data.success) {
                emits('update-list')
                onCancel()
              }
              onsaveloading.value = false
            })
            break
          case 3:
            onsaveloading.value = true
            finishOrder(data).then((res) => {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  type: res.data.success ? 'success' : 'error',
                  duration: 3000,
                })
              if (res?.data.success) {
                emits('update-list')
                onCancel()
              }
              onsaveloading.value = false
            })
            break
          case 4:
            onsaveloading.value = true
            cancelOrder(data).then((res) => {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  type: res.data.success ? 'success' : 'error',
                  duration: 3000,
                })
              if (res?.data.success) {
                emits('update-list')
                onCancel()
              }
              onsaveloading.value = false
            })
            break
          case 5:
            let data1: any = {
              content: ruleForm.content,
              workIds: selecttion.value,
            }
            onsaveloading.value = true
            saveReminder(data1).then((res) => {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  type: res.data.success ? 'success' : 'error',
                  duration: 3000,
                })
              if (res?.data.success) {
                emits('update-list')
                onCancel()
              }
              onsaveloading.value = false
            })
            break
          case 6:
            let emp = {
              empId: ruleForm.empId,
              remark: ruleForm.note,
              workId: selecttion.value[0],
            }
            onsaveloading.value = true
            changeServiceEmp(emp).then((res) => {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  type: res.data.success ? 'success' : 'error',
                  duration: 3000,
                })
              if (res?.data.success) {
                emits('update-list')
                onCancel()
              }
              onsaveloading.value = false
            })
            break
          case 7:
            let temp = {
              changeToNetworkEmpId: null,
              changeToNetworkId: ruleForm.website,
              currentNetworkId: networkId.value,
              remark: ruleForm.note,
              workId: selecttion.value[0],
            }
            onsaveloading.value = true
            changeNetwork(temp).then((res) => {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  type: res.data.success ? 'success' : 'error',
                  duration: 3000,
                })
              if (res?.data.success) {
                emits('update-list')
                onCancel()
              }
              onsaveloading.value = false
            })
            break
          case 8:
            orderArchived(data).then((res) => {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  type: res.data.success ? 'success' : 'error',
                  duration: 3000,
                })
              if (res?.data.success) {
                emits('update-list')
                onCancel()
              }
              onsaveloading.value = false
            })
            break
        }
      } else {
        return false
      }
    })
  }
  const onCancel = () => {
    formRef.value.resetFields()
    ruleForm.note = ''
    formValidateResult.value = {
      empId: true,
    }
    emits('assign-dialog')
  }

  const formValidateResult = ref({
    empId: true,
  })
  const handleFormValidate = (prop: FormItemProp, isValid: boolean) => {
    if (prop === 'empId') {
      formValidateResult.value.empId = isValid
    }
  }

  watch(assignAny, (n) => {
    switch (n) {
      case 1:
      case 6:
        getworkTeamPageSelect('')
        break
      case 2:
      case 7:
        getNetworkPageSelectList('')
        break
    }
  })

  watch(
    () => ruleForm.website,
    (n) => {
      ruleForm.cusId = ''
      if (n) {
        getNetworkEmpPageSelectList('')
      }
    },
  )
</script>

<style lang="scss" scoped>
  :deep(.el-textarea) {
    .el-textarea__inner {
      min-height: 75px !important;
      max-height: 200px !important;
      min-width: 250px;
      max-width: 450px;
      overflow: hidden;
    }
  }

  .form_content {
    .form_item {
      margin-bottom: 12px;
    }

    .validate_fail {
      margin-bottom: 24px;
      transition: all 0.4s;
    }
  }

  .el-form-item {
    margin-bottom: 16px;
    margin-top: 10px;

    :deep(.el-form-item__label) {
      font-size: 12px;
    }

    .notes {
      width: 100%;
    }
  }

  :deep(.alert) {
    padding: 4px;
  }

  :deep(.inputread) {
    width: 182px;
  }

  .footer {
    margin-top: 40px;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .btn_save {
      width: 60px;
    }
  }

  @import '../index.scss';
</style>
